package zhongbo.java.air.flightpath.listener;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import zhongbo.java.air.flightpath.mapper.FlightPathMapper;
import zhongbo.java.air.flightpath.model.FlightPath;

import java.util.UUID;

@Component
@Slf4j
public class RedisSubscribeLogChanelListener implements MessageListener {
    @Autowired
    private FlightPathMapper flightPathMapper;
    @Autowired
    private RedisLogChanelPublisher redisLogChanelPublisher;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        try {
            String channel = new String(message.getChannel());
            String body = new String(message.getBody());
            log.info("收到Redis日志消息 - 频道: {}, 内容: {}", channel, body);

            FlightPath flightPath = convertToFlightPath(body);
            redisLogChanelPublisher.publishMessage(flightPath.toString());
//            if (flightPath != null) {
//                int insert = flightPathMapper.insert(flightPath);
//                if (insert > 0) {
//                    log.info("成功保存FlightPath数据: {}", flightPath);
//                    redisLogChanelPublisher.publishMessage(flightPath.toString());
//                }
//                log.info("保存失败！");
//            }
        } catch (Exception e) {
            log.error("处理Redis消息失败", e);
        }
    }

    private FlightPath convertToFlightPath(String body) {
        try {
            JSONObject jsonObject = JSONUtil.parseObj(body);
            FlightPath flightPath = new FlightPath();
            // 基本字段
            flightPath.setIcaoCode(jsonObject.getStr("icao_code"));
            flightPath.setSpeed(jsonObject.getStr("speed"));
            flightPath.setHeading(jsonObject.getShort("heading"));
            flightPath.setTimestamp(jsonObject.getDate("timestamp"));
            flightPath.setAltitude(jsonObject.getInt("altitude"));
            flightPath.setLatitude(jsonObject.getDouble("latitude"));
            flightPath.setLongitude(jsonObject.getDouble("longitude"));
            flightPath.setId(UUID.randomUUID().toString());
            flightPath.setSourceType(jsonObject.getStr("source_type"));
            log.info("转换后的 FlightPath: {}", flightPath);
            return flightPath;
        } catch (Exception e) {
            log.error("转换JSON到FlightPath失败 - 原始内容: {}", body, e);
            return null;
        }
    }
}